package com.pangolin.pangolinim.ui.fragment;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.lqr.recyclerview.LQRRecyclerView;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.sqlite.DBContact;
import com.pangolin.pangolinim.ui.activity.MainActivity;
import com.pangolin.pangolinim.ui.activity.NewFriendActivity;
import com.pangolin.pangolinim.ui.adapter.ContactsAdapter;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.base.BaseFragment;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.ImageUtil;
import com.pangolin.pangolinim.utils.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ContactsFragment extends BaseFragment {
    public LQRRecyclerView mRvContacts;
    private ContactsAdapter mAdapter;

    public static List<UIContact> mContacts =  new ArrayList<UIContact>();

    private LinearLayout mllNewFriend;
    private TextView mTvNewFriendUnread;

    @Override
    public void init(){
    }

    @Override
    public void initView(View rootView) {
        mRvContacts = rootView.findViewById(R.id.rvContacts);
        mTvNewFriendUnread = rootView.findViewById(R.id.tvNewFriendUnread);
        mllNewFriend = rootView.findViewById(R.id.llNewFriend);
        setAdapter();
    }

    @Override
    public void onResume() {
        super.onResume();
        //消息提醒同步MainActivity的底部标签
        mTvNewFriendUnread.setVisibility(((MainActivity) getActivity()).mTvContactRedDot.getVisibility());
        // 发送获取联系人列表请求
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_CONTACTS);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        ((MainActivity)getActivity()).BroadcastSender(bundleUtil.getBundle());
    }

    @Override
    public void onPause() {
        super.onPause();
        //Logger.d("ContactsFragment onPause");
    }

    @Override
    public void initData() {
    }

    @Override
    public void initListener() {
        mllNewFriend.setOnClickListener(v -> {
            ((MainActivity) getActivity()).jumpToActivity(NewFriendActivity.class , GsonUtil.toJson(((MainActivity)getActivity()).me));
            removeUnread();
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_contacts;
    }

    private void setAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRvContacts.setLayoutManager(layoutManager);
        mAdapter = new ContactsAdapter(mContacts , ((MainActivity)getActivity()).me);
        mRvContacts.setAdapter(mAdapter);
    }

    /**
     * TODO:更新联系人列表。为提高效率，如果已经有列表，则会判断新旧联系人信息是否一致，只更新不一致的部分。
     * @param contacts 要更新的联系人列表
     */
    public void setContacts(List<DBContact> contacts){
        MainActivity activity = (MainActivity) getActivity();
        for (DBContact dbContact : contacts){
            //查找现有列表中是否有这个用户
            int i = findContactById(dbContact.getUid());
            if(i >= 0){
                //判断现有列表中联系人信息和dbCntact是否一致，不一致更新信息
                if(!dbContact.getName().equals(mContacts.get(i).getName())){
                    mContacts.get(i).setName(dbContact.getName());
                }
                if(!dbContact.getHeadimg().equals(mContacts.get(i).getHeader())){
                    mContacts.get(i).setHeader(dbContact.getHeadimg());
                    File file = new File(activity.getExternalFilesDir(String.valueOf(activity.me.getUid())) , dbContact.getHeadimg());
                    if(file.exists() && file.isFile()){
                        mContacts.get(i).setBitHeader(ImageUtil.getBitmapFromFile(activity , file , 120 , 120));
                    }
                }else{
                    //判断头像bitmap是否为空，如果为空则重新尝试读取头像
                    if(mContacts.get(i).getBitHeader() == null){
                        File file = new File(activity.getExternalFilesDir(String.valueOf(activity.me.getUid())) , dbContact.getHeadimg());
                        if(file.exists() && file.isFile()){
                            mContacts.get(i).setBitHeader(ImageUtil.getBitmapFromFile(activity , file , 120 , 120));
                        }
                    }
                }
            }else{
                //如果没有，直接创建这个联系人信息
                UIContact uiContact = new UIContact();
                uiContact.setUid(dbContact.getUid());
                uiContact.setName(dbContact.getName());
                uiContact.setHeader(dbContact.getHeadimg());
                uiContact.setType(5);
                File file = new File(activity.getExternalFilesDir(String.valueOf(activity.me.getUid())) , uiContact.getHeader());
                if(file.exists() && file.isFile()){
                    uiContact.setBitHeader(ImageUtil.getBitmapFromFile(activity , file , 120 , 120));
                }
                mContacts.add(uiContact);
            }
        }
        //反向查找已经删除的条目
        Iterator item = mContacts.iterator();
        while (item.hasNext()) {
            UIContact contact = (UIContact) item.next();
            int flag = -1;
            for (int j = 0 ; j < contacts.size() ; j ++){
                if (contacts.get(j).getUid() == contact.getUid()){
                    flag = j;
                    break;
                }
            }
            if(flag < 0){
                item.remove();
            }
        }
        if(mAdapter != null){
            mAdapter.notifyDataSetChanged();
        }
    }

    private int findContactById(int uid){
        for (int i = 0 ; i < mContacts.size() ; i ++){
            if (mContacts.get(i).getUid() == uid){
                return i;
            }
        }
        return -1;
    }

    public void setUnread(){
        if(mTvNewFriendUnread != null){
            mTvNewFriendUnread.setVisibility(View.VISIBLE);
        }
    }

    public void removeUnread(){
        MainActivity activity = (MainActivity) getActivity();
        if (activity != null){
            ((MainActivity) getActivity()).mTvContactRedDot.setVisibility(View.GONE);
        }
        if(mTvNewFriendUnread != null){
            mTvNewFriendUnread.setVisibility(View.GONE);
        }
    }
}